package edu.ucsur.tp.contactcenter.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import edu.ucsur.tp.beans.UsuarioBean;
import edu.ucsur.tp.negocio.mantenimientos.UsuarioNego;


/**
 * Servlet implementation class LoginUsuario
 */
@WebServlet("/LoginUsuario")
public class LoginUsuario extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginUsuario() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    
    /**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String action = request.getParameter("action");
		response.setContentType( "text/html" );
		PrintWriter out = response.getWriter();
		
		if (action.equals("logout")){
			out.println("Entro : " + action );
			HttpSession sesion = request.getSession(true);
			sesion.setAttribute("UserLogin", null);
			response.sendRedirect("login.jsp");
		}
	}
    

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		//login
		UsuarioNego oUserNego = new UsuarioNego();
		
		String user = request.getParameter("txtUser");
		String pass = request.getParameter("txtPass");
		
		//response.setContentType("text/html");
	    //PrintWriter out = response.getWriter();

	    //out.println("Test : 001");

		
		if (oUserNego.loginUsuario(user, pass)==true){
			//Login OK
			HttpSession sesion = request.getSession(true);
			UsuarioBean oUser = oUserNego.getUsuario(user); 
			sesion.setAttribute("UserLogin", oUser);
			response.sendRedirect("main.jsp");
			
		} else {
			
			HttpSession sesion = request.getSession(true);
			sesion.setAttribute("UserLogin", null);
			response.sendRedirect("login.jsp?motivo=fail");
		}
		
	}

}
